<template>
  <section>
    <el-row style="margin:8px 0;font-weight: bold">
      <el-col :span="4"><span>规格属性：</span></el-col>
      <el-col :span="20">
        <el-tag size="small" style="margin:0 2px;" :key="specification.txt" v-for="specification in specifications" closable :disable-transitions="false" @close="handleClose(specification)">
          {{specification.txt}}
        </el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="mini" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
        </el-input>
        <el-button v-else v-show="specificationDetail.length==0" class="button-new-tag" size="mini" @click="showInput"> + </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table :data="specificationDetail" ref="sepcTable" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column v-for="specification in specifications" :key="specification.txt" :label="specification.txt">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" size="mini" v-model="specification.data[scope.$index]"></el-input>
            <span v-if="!scope.row.edit">{{specification.data[scope.$index]}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="产品编号" width="200" >
          <template slot-scope="scope">
            <div class="sn-box" v-if="scope.row.edit" >
              <el-input v-model="scope.row.sn" size="mini"/>
              <el-button @click='creatNumber(scope)' size="mini" type="text">生成</el-button>
            </div>
            <span v-else size="mini">{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="data.unit" label="单位"  width="80">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" v-model="scope.row.data.unit" size="mini"/>
            <span v-else size="mini" slot="reference">{{scope.row.data.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="155">
          <template slot-scope="scope">
            <el-button :type="scope.row.edit?'success':'primary'" v-if="!scope.row.id" @click='addSpecBtn(scope)' size="mini" icon="edit">保存</el-button>
            <el-button :type="scope.row.edit?'success':'primary'" v-if="scope.row.id" @click='editSpecBtn(scope.row)' size="mini" icon="edit">{{scope.row.edit?'保存':'编辑'}}</el-button>
            <el-button @click='cancelSpecBtn(scope)' size="mini" v-if="scope.row.edit">取消</el-button>
            <el-button @click='delSpecBtn(scope)' size="mini" type="danger" v-if="scope.row.id && !scope.row.edit">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row style="margin-top:10px;">
      <el-button size="mini" @click="addSpecifications" type="primary" icon="el-icon-plus"/>
    </el-row>
  </section>
</template>

<script>
  import errHandler from '@/assets/errHandler.js'
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import Vue from 'vue'//后续添加属性，需要vue联动
  export default {
    name: "productSpec",
    props:['productId'],
    data() {
      return {
        inputVisible: false,
        inputValue: '',
        specifications:[],//各种规格
        specificationDetail:[],
        currProduct:null
      }
    },
    created() {
      this.getCurrProduct(this.productId)
    },
    mounted() {
    },
    computed: {
      ...mapGetters(['department']),
    },
    watch: {
      productId(nv,ov){
        if(nv){
          this.getCurrProduct(nv)
        }
      }
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      getCurrProduct(id){
        this.fetch({name:"getProduct",data:{id}})
          .then(res=>{
            console.log('当前产品----',res)
            this.currProduct=res
            this.specificationDetail=res.productSpecs
            this.specifications=[]
            if(res.productSpecs.length>0){
              this.makePropsUi(res.productSpecs)
            }
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makePropsUi(specs){
        let prop =[]
        specs.forEach(spec=>{
          let propKV = spec.props.split(';')
          if(propKV.length>0){
            let item =[]
            propKV.forEach(pKV=>{
              let pkv=pKV.split(':')
              let tmp={txt:'',data:[]}
              tmp.txt=pkv[0]
              tmp.data.push(pkv[1])
              item.push(tmp)
            })
            prop.push(item)
          }
        })
        if(prop.length > 1){
          for(let i=1;i<prop.length;i++){
            let proptmp=prop[i]
            proptmp.forEach(pt=>{
              prop[0].forEach(p=>{
                if(pt.txt === p.txt){
                  p.data = p.data.concat(pt.data)
                }
              })
            })
          }
        }
        this.specifications=prop[0]
        console.log(this.specifications)
      },
      handleSelectionChange(vals){
        this.skuSelection = vals
      },
      handleClose(tag) {
        this.specifications.splice(this.specifications.indexOf(tag), 1)
      },
      handleInputConfirm() {
        let inputValue = this.inputValue
        if (inputValue) {
          this.specifications.push({txt:inputValue,data:[]})
        }
        this.inputVisible = false
        this.inputValue = ''
      },
      showInput() {
        this.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      creatNumber(scope){
        console.log(scope)
        this.fetch({name:"createSn",data:{snType:16}})
          .then(res=>{
            console.log(res)
            scope.row.sn = res.sn
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      copySn(sn){
        this.specificationDetail.forEach(s=>{
          if(s.sn !==sn){
            s.sn=sn
            s.edit = true
          }
        })
      },
      addSpecifications(){//增加规格
        console.log('增加规格')
        let tmp = {price:'0',sn:'',edit:true,data:{unit:this.currProduct.data.unit}}
        this.specificationDetail.push(tmp)
        //新建规格
      },
      editSpecBtn(row){
        if(row.edit === undefined){
          Vue.set(row,'edit',true)//后续添加属性，需要vue联动
          return
        }
        if(row.edit){
          this.loading=true
          this.updateProductSpec(row)
        }else {
          row.edit=true
        }
      },
      updateProductSpec(row){
        console.log(row)
        this.fetch({name:"updateProductSpec",data:{...row}})
          .then(res=>{
            console.log(res)
            this.$message({type:'success',message:'保存成功！'})
            row.edit = false
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      cancelSpecBtn(scope){
        if(scope.row.id === undefined){
          this.specificationDetail.splice(scope.$index,1)
          return
        }
        if(scope.row.edit === undefined){
          Vue.set(scope.row,'edit',false)//后续添加属性，需要vue联动
        }else {
          scope.row.edit =false
        }
      },
      delSpecBtn(scope){
        console.log('看下有没有id--------',this.specifications)
        this.$confirm('确认删除？')
          .then(()=> {
            this.fetch({name:"delProductSpec",data:{id:scope.row.id}})
              .then(res=>{
                this.loading=false
                this.specificationDetail.splice(scope.$index,1)
                this.specifications.forEach(s=>{
                  s.data.splice(scope.$index,1)
                })
              })
              .catch(err=>{
                console.log(err)
                errHandler.handle(this,err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
            this.loading = false
          })
      },
      addSpecBtn(scope){//确定规格按钮判断编辑还是新建
        // console.log(scope)
        let props = this.makeProps(scope.row,scope.$index)
        let data={...scope.row,props,productId:this.productId}
        this.fetch({name:"createProductSpec",data})
          .then(res=>{
            console.log(res)
            this.$message({type:'success',message:'新建成功！'})
            scope.row.id=res.id
            scope.row.edit=false
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeProps(row,index){
        console.log(row)
        console.log(this.specifications)
        let tmp=''
        this.specifications.forEach(spec=>{
          tmp +=spec.txt+':'+spec.data[index]+';'
        })
        if(tmp.length>0)
          tmp = tmp.substring(0,tmp.length-1)
        return tmp
      },
      createProductSpec(data){
      },
    }
  }
</script>

<style scoped>
.sn-box{
  display: flex;
  flex-direction: row;

}
</style>
